package com.coocare.licence.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coocare.licence.config.CacheConstants;
import com.coocare.licence.config.domain.AjaxResult;
import com.coocare.licence.config.plugins.logging.annotation.Logging;
import com.coocare.licence.config.resolver.ParamResolver;
import com.coocare.licence.config.tenant.TenantBroker;
import com.coocare.licence.entity.SysTenant;
import com.coocare.licence.service.ISysMenuService;
import com.coocare.licence.service.ISysTenantService;
import com.coocare.licence.utils.PageDomain;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author adam
 * @create 2024/4/22 下午1:52
 */

@Tag(name = "租户管理")
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys/tenant")
public class SysTenantController {

    private final ISysTenantService tenantService;
    private final ISysMenuService menuService;

    /**
     * 分页查询
     * @param pageDomain 分页对象
     * @param name 租户
     * @return
     */
    @GetMapping("/page")
    public AjaxResult getSysTenantPage(String name, PageDomain pageDomain) {
        return AjaxResult.ok(tenantService.page(new Page<>(pageDomain.getPageNo(), pageDomain.getPageSize()), Wrappers.<SysTenant>lambdaQuery()
                .like(StrUtil.isNotBlank(name), SysTenant::getName, name)));
    }

    /**
     * 通过ID 查询租户信息
     * @param id ID
     * @return R
     */
    @GetMapping("/details/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        return AjaxResult.ok(tenantService.getById(id));
    }

    /**
     * 新增租户
     * @param sysTenant 租户
     * @return R
     */
    @Logging("新增租户")
    @PostMapping()
    @CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
    public AjaxResult save(@RequestBody SysTenant sysTenant) {
        return AjaxResult.ok(tenantService.saveTenant(sysTenant));
    }

    /**
     * 修改租户
     * @param sysTenant 租户
     * @return R
     */
    @Logging("修改租户")
    @PutMapping()
    public AjaxResult updateById(@RequestBody SysTenant sysTenant) {
        return AjaxResult.ok(tenantService.updateTenant(sysTenant));
    }

    /**
     * 通过id删除租户
     * <p>
     * 为了保证安全,这里只删除租户表的数据，不删除基础表中的租户初始化数据。
     * @param ids id 列表
     * @return R
     */
    @Logging("删除租户")
    @DeleteMapping
    @CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
    public AjaxResult removeById(@RequestBody Long[] ids) {
        return AjaxResult.ok(tenantService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * 查询全部有效的租户
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list() {
        List<SysTenant> tenants = tenantService.getNormalTenant()
                .stream()
                .filter(tenant -> tenant.getStartTime().isBefore(LocalDateTime.now()))
                .filter(tenant -> tenant.getEndTime().isAfter(LocalDateTime.now()))
                .collect(Collectors.toList());
        return AjaxResult.ok(tenants);
    }

    @GetMapping(value = "/tree/menu")
    public AjaxResult getTree() {
        Long defaultId = ParamResolver.getLong("TENANT_DEFAULT_ID", 1L);
        List<Tree<Long>> trees = new ArrayList<>();
        TenantBroker.runAs(defaultId, (id) -> {
            trees.addAll(menuService.treeMenu(null, null, null));
        });

        return AjaxResult.ok(trees);
    }
}
